package caches;

import java.util.AbstractMap;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

public class EfficientResultCache<K, V> implements Cache<K, V> {

	private ConcurrentHashMap<K, Entry<V, Long>> map = new ConcurrentHashMap<>();
	private long lifeTime;
	
	public EfficientResultCache(long lifeTimeInMillis) {
		this.lifeTime = lifeTimeInMillis;
	}
	
	@Override
	public V get(K key) {
		Entry<V, Long> value = map.get(key);
		
		if (value != null) {
			if (System.currentTimeMillis() - value.getValue() > lifeTime) {
				// potentional race condition
				map.remove(key);
				return null;
			} else
				return value.getKey();
		} else 
			return null;
	}

	@Override
	public void put(K key, V value) {
		map.putIfAbsent(key, new AbstractMap.SimpleEntry<V, Long>(value, System.currentTimeMillis()));		
	}
}
